import java.util.*;

//二叉树的锯齿形层序遍历
//https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/description/
public class Test {
    public static void main(String[] args) {
        //
    }
}



//Definition for a binary tree node.
class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }

 //还有一个思路：既然之前的行序遍历，是利用了队列的先进先出特性，那么，这个，能否同时利用队列和栈的特性？？？
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();//工具
        queue.add(root);
        boolean flg = true;
        while (!queue.isEmpty()) {
            int len = queue.size();
            List<Integer> list = new ArrayList<>();//记录每一行的数据
            for (int i = 0; i < len; i++) {
                //flg = !flg;
                TreeNode node = queue.poll();
                list.add(node.val);
                /*for(TreeNode child:node.children ){

                }*/
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            /*if(flg)
                list = reverse(list,len);
            ret.add(list);*/
            if(flg)
                Collections.reverse(list);
            flg = !flg;
        }
        return ret;
    }

    //逆序函数
     List<Integer> reverse (List<Integer> list,int size) {
        List<Integer> ret = new ArrayList<>();
        LinkedList<Integer> rev = new LinkedList<>();
        //queue.get();
         for(int i = list.size()-1;i>=0;i--){
             rev.add(list.get(i));
         }
         return rev;
     }
}